<template>
  <div>
    <button @click="connect">连接 WebSocket</button>
    <input v-model="message" @keyup.enter="send">
    <div>收到的消息: {{ receivedMessage }}</div>
  </div>
</template>

<script>
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';

export default {
  data() {
    return {
      stompClient: null,
      message: '',
      receivedMessage: ''
    };
  },
  methods: {
    connect() {
      const socket = new SockJS('http://localhost:8080/ws');
      this.stompClient = Stomp.over(socket);

      this.stompClient.connect({}, () => {
        // 订阅公共频道（广播）
        this.stompClient.subscribe('/topic/public', (msg) => {
          this.receivedMessage = msg.body;
        });

        // 订阅私有频道（需服务端调用 convertAndSendToUser）
        this.stompClient.subscribe('/user/queue/private', (msg) => {
          this.receivedMessage = '[私信] ' + msg.body;
        });
      });
    },
    send() {
      if (this.stompClient) {
        this.stompClient.send("/app/send", {}, this.message);
        this.message = '';
      }
    }
  },
  beforeDestroy() {
    if (this.stompClient) {
      this.stompClient.disconnect();
    }
  }
};
</script>